package com.szcinda.controller.RSAUtil;

import sun.misc.BASE64Decoder;

import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.codec.binary.Base64;

/**
 * 签名验签工具类
 */
public class RSAUtils {
    public static final String KEY_ALGORITHM = "RSA";
    public static final String PUBLIC_KEY = "RSAPublicKey";
    public static final String PRIVATE_KEY = "RSAPrivateKey";
    public static final String SIGNATURE_ALGORITHM = "MD5withRSA";

    // public static String publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC8XBmLw73DWPAjdpLm85YGUcxDRmpYyqAw3r8DimX2Kbw4IlwxRJ8jbyRM+shq8LcA0xbDIyjmXToFREKU+cawnF+TG5KkhHZ/db5hsziEbkglVfbn7zl6qI9h68PEQZ235GiN9ygWf0uXNQnH3uIzza+cIGqtIAf39aQ5A7TyywIDAQAB";
    // public static String privateKey = "MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBALxcGYvDvcNY8CN2kubzlgZRzENGaljKoDDevwOKZfYpvDgiXDFEnyNvJEz6yGrwtwDTFsMjKOZdOgVEQpT5xrCcX5MbkqSEdn91vmGzOIRuSCVV9ufvOXqoj2Hrw8RBnbfkaI33KBZ/S5c1Ccfe4jPNr5wgaq0gB/f1pDkDtPLLAgMBAAECgYBBahrVFx2IAhMjvcI2wtGPUEkH9CRqwbPwROtBZ4cRfl0HgadS1OoPfEG3GkEQIpjriGOXUVaa6jWELriQ1E3T3ngoCaBoPJTqdWn8eUPEwprbitiSLSMtCA3+PsPqKKJ2SZpmYwhNuFgAzzvGAX1DNkoQebE27APHjF4N3MxIwQJBAPYHDCBh5hvfBfCOf+Vmc/Fb61Cu582HCdGBmOT3dAFIuAJlUMX6Z1+x5+4jMv/J38nktsZRIfHzEnauJp02ieUCQQDD/qbQn6vQ6dHETgFC4o2r/OTsT1KU0HhzxOsqljlBLgydWSwf05prkjQCdmeNFZNpl+PHrerz1SYaByS5hf7vAkAl1UOaHzPhiVRCf8dPIYgmz3nKOHtQ8bkizIkUfLEMGYCiba4UI8ONxa/iwOrwxrxxMYihyowrxrNKKNGrT125AkBQFEbiLKsN48sSUvDO/DP4Vo7OQqayKO9eFdIkB1cDW6ZJz/poUpPgac8YRnqOuYcOeMHXfyblU2yK6+pEZww/AkB4OHi0lx7nWkb6a1e/u/RtH6T4Foj+0OeUy4Xd+Csl3vRQeMBRB9vzt+AVBSDSu4N3KPEkH0JqZz96LTlV2tjF";

    public static String publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDBgh0GWBNg5kS6YmtTQbLfgxlzuNPoDMC/YkHRLkMLqQE8I8UUAi2FnaQIV1hKAPv7adaSSVuO5CJ/FMDfmdOaePABFrCX6OiYvLm0TlZPCm8BZJ0UzdpWuN5PLtqZPV0D3eyFRl6WK5LtWKX2LQXf7og4u9IAMiRr11t+DnE93wIDAQAB";
    public static String privateKey = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAMGCHQZYE2DmRLpia1NBst+DGXO40+gMwL9iQdEuQwupATwjxRQCLYWdpAhXWEoA+/tp1pJJW47kIn8UwN+Z05p48AEWsJfo6Ji8ubROVk8KbwFknRTN2la43k8u2pk9XQPd7IVGXpYrku1YpfYtBd/uiDi70gAyJGvXW34OcT3fAgMBAAECgYBeu6gh9vRlt9VludD5DWzYZ4IKWS3EqJmkGCJImfFQwAhOvOQ6i2Zlx2sKelhKwniZ+JKHQ0qDhcQtmqdh0Bj65rNZdwy4ozh1ZzGCSuOZur1XT+RuQUafsaksfqnWuIqnSlMSydwgMAHYzxf5gaBmbcLGTBv/xEH/2x3qwVLcYQJBAP/0PAphA1+XRsHLC6RB617+kn4GaSdT8q5Ir6fCgqygHmkACU2Lnj6mateoVEZm+U7XCa1FR5x407kBuUpdL00CQQDBiwImBJRglXTV4t6yAv10jPtaq36ij3J/Q2PIJxPluEUR5ppRHO8VaMj3piUxAJBmncc+Bc/p0buyPHyLq2PbAkBZ9oNf9odUAvzowrBd1JmhMwNUbnZpT1VeMsgiw/hgKotlxpB+hBNj2+Rz1oOAl1MLhgOttkscUU/BmDyDScuFAkEAvcZVC/wvlWjXECaNoFTIO3FFwYko+bLYXSsx+v8+RmDh8QSBygkp8X82l4YlL6BS9xu8UveV/7o0ZjdjE/yxQwJAXUM/PtSdZ9jvthl7eT0UNzXSgApnaLPpW6Qg6nulaPilQAWnDq9enphL6tsUu6gxSH0hOzss9+LJxBa2v7sDmA==";

    public static Map<String, Object> initKey() throws Exception {
        KeyPairGenerator keyPairGen = KeyPairGenerator
                .getInstance(KEY_ALGORITHM);
        keyPairGen.initialize(1024);
        KeyPair keyPair = keyPairGen.generateKeyPair();
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
        Map<String, Object> keyMap = new HashMap<String, Object>(2);
        keyMap.put(PUBLIC_KEY, publicKey);
        keyMap.put(PRIVATE_KEY, privateKey);
        // 得到公钥字符串
        String publicKeyStr = new String(Base64.encodeBase64(publicKey.getEncoded()));
        // 得到私钥字符串
        String privateKeyStr = new String(Base64.encodeBase64((privateKey.getEncoded())));

        System.out.println("随机生成的公钥为:" + publicKeyStr);
        System.out.println("随机生成的私钥为:" + privateKeyStr);
        return keyMap;
    }

    //获取公钥
    public static PublicKey getPublicKey(String key) throws Exception {
        byte[] keyBytes;
        keyBytes = (new BASE64Decoder()).decodeBuffer(key);
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        return keyFactory.generatePublic(keySpec);
    }

    //获取私钥
    public static PrivateKey getPrivateKey(String key) throws Exception {
        byte[] keyBytes;
        keyBytes = (new BASE64Decoder()).decodeBuffer(key);
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        return keyFactory.generatePrivate(keySpec);
    }

    //***************************签名和验证*******************************
    public static byte[] sign(byte[] data, String privateKeyStr) throws Exception {
        PrivateKey priK = getPrivateKey(privateKeyStr);
        Signature sig = Signature.getInstance(SIGNATURE_ALGORITHM);
        sig.initSign(priK);
        sig.update(data);
        return sig.sign();
    }

    public static boolean verify(byte[] data, byte[] sign, String publicKeyStr) {
        try {
            PublicKey pubK = getPublicKey(publicKeyStr);
            Signature sig = Signature.getInstance(SIGNATURE_ALGORITHM);
            sig.initVerify(pubK);
            sig.update(data);
            return sig.verify(sign);
        } catch (Exception e) {
            return false;
        }
    }

    public static void main(String[] args) throws Exception {
        initKey();
//        String str = "DFG659004";
//        System.out.println("\n原文:" + str);
//        byte[] signature1 = sign(str.getBytes(), privateKey);
//        String text = Base64.encodeBase64String(signature1);
//        System.out.println(String.format("私钥签名后的文本：%s", text));
//        byte[] signature2 = Base64.decodeBase64(text);
//        boolean status = verify(str.getBytes(), signature2, publicKey);
//        System.out.println("验证情况：" + status);
    }
}
